const db = uniCloud.database();
const dbCmd = db.command;
const $ = db.command.aggregate;
module.exports = async function(options = {}) {
	const { characterId } = options;
	const token = this.getUniIdToken();
	if (!token || !characterId) {
		throw new Error('非法访问');
	}
	let [chapterListCustom] = await Promise.all([
		db.collection('a-dz-chapter-list-custom').aggregate()
		.match({
			characterId
		})
		.lookup({
			from: 'a-dz-category-list-custom',
			let: {
				mainid: '$chapter'
			},
			pipeline: $.pipeline().match(dbCmd.expr($.and([
				$.eq(['$chapter', '$$mainid']),
			]))).done(),
			as: 'categoryList'
		})
		.lookup({
			from: 'a-dz-course-list-custom',
			let: {
				mainid: '$chapter'
			},
			pipeline: $.pipeline().match(dbCmd.expr($.and([
				$.eq(['$chapter', '$$mainid']),
			]))).done(),
			as: 'courseList'
		})
		.project({
			name: 1,
			chapter: 1,
			chapterDesc: 1,
			logo: 1,
			createTime: 1,
			courseCount: $.size('$courseList'),
			categoryList: '$categoryList',
			categoryCount: $.size('$categoryList'),
			type: 'CUSTOM'
		}).end()
	])
	return {
		code: 0,
		data: chapterListCustom.data,
		msg: '获取成功'
	}
}